from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
from PIL import Image


class SimpleHTTPRequestHandlerWithImage(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path == '/image':
            # 创建一个简单的图片，这里以1x1像素的纯红色图片为例
            img = Image.new('RGB', (1, 1), color='red')
            output = BytesIO()
            img.save(output, format='JPEG')
            data = output.getvalue()

            # 设置响应头
            self.send_response(200)
            self.send_header('Content-type', 'image/jpeg')
            self.end_headers()

            # 发送图片数据
            self.wfile.write(data)
        else:
            self.send_error(404, 'File not found')


if __name__ == '__main__':
    httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandlerWithImage)
    print("Serving at http://localhost:8000")
    httpd.serve_forever()